package com.hyt.it.ogt.ykcj.utils;

import cn.hutool.core.io.FileUtil;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.RectangleReadOnly;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

@Slf4j
public class PdfManager {

    public static File imageToPdf(File imageFile) {
        File pdfFile = FileUtil.createTempFile(".pdf", Boolean.TRUE);
        pdfFile.deleteOnExit();

        Document doc = null;
        try {
            Image png1 = Image.getInstance(FileUtil.readBytes(imageFile));
            float height = png1.getHeight();
            float width = png1.getWidth();
            
            doc = new Document(new RectangleReadOnly(width, height), 0, 0, 0, 0);
            PdfWriter.getInstance(doc, FileUtil.getOutputStream(pdfFile));
            
            doc.open();
            doc.newPage();
            png1.setAlignment(Image.MIDDLE);
            
            doc.add(png1);
        } catch (Exception e) {
            log.error("# PDF文件生成异常", e);
        } finally {
            if (doc != null) {
                doc.close();
            }
        }

        return pdfFile;
    }

    public static File imageToPdf(File... imageFiles) {
        File pdfFile = FileUtil.createTempFile(".pdf", Boolean.TRUE);
        pdfFile.deleteOnExit();

        Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
        try {
            PdfWriter.getInstance(doc, FileUtil.getOutputStream(pdfFile));
            doc.open();
            for (File imageFile : imageFiles) {
                doc.newPage();
                Image png1 = Image.getInstance(FileUtil.readBytes(imageFile));
                float height = png1.getHeight();
                float width = png1.getWidth();
                float percent = getPercent2(height, width);
                png1.setAlignment(Image.MIDDLE);
                png1.scalePercent(percent + 3);// 表示是原来图像的比例;
                doc.add(png1);
            }
        } catch (Exception e) {
            log.error("# PDF文件生成异常", e);
        } finally {
            doc.close();
        }

        return pdfFile;
    }

    /**
     * 第一种解决方案 在不改变图片形状的同时，判断，如果h>w，则按h压缩，否则在w>h或w=h的情况下，按宽度压缩
     *
     * @param h
     * @param w
     * @return
     */

    public static int getPercent(float h, float w) {
        int p = 0;
        float p2 = 0.0f;
        if (h > w) {
            p2 = 297 / h * 100;
        } else {
            p2 = 210 / w * 100;
        }
        p = Math.round(p2);
        return p;
    }

    /**
     * 第二种解决方案，统一按照宽度压缩 这样来的效果是，所有图片的宽度是相等的，自我认为给客户的效果是最好的
     */
    public static float getPercent2(float h, float w) {
        float p = 0.0f;
        float p2 = 0.0f;
        p2 = 530f / w * 100f;
        p = Math.round(p2);
        return p;
    }
}
